#!C:\Python33
# -*- coding: utf-8 -*-

import uniforme
import swanson_and_megill
import pearson_and_tuckey
import beta
import triangular
import normal
from datetime import datetime


_initial=8
_final=80


_filePath = ''


_upper_threshold_Boehm=1.5
_middle_threshold_Boehm=1.0
_lower_threshold_Boehm=0.67

' This will serve as a container for the classes that implement different distributions used for calculations '
_distList = []


'''
    Modify this method adding the distribution's class you've developed
    Each class must have two methods:
        + media(self, valor_pes, valor_opt=None, mediana=None)
        + varianza(self, valor_pes, valor_opt=None, mediana=None):
    This methods implement the definition of mean and variance for your distribution 
'''
def loadDistributions():
    _distList.append(['Uniforme', uniforme.uniforme()])
    _distList.append(['Swanson and Megill', swanson_and_megill.SwansonMegill()])
    _distList.append(['Pearson and Tuckey', pearson_and_tuckey.PearsonTuckey()])
    _distList.append(['Triangular',triangular.Triangular()])
    _distList.append(['Beta',beta.Beta()])
    _distList.append(['Normal',normal.Normal()])
    #_distList.append(['My Distribution', myDistModule.myDistClass()])

'''
   For each distribution defined return the mean and variance for every hour between _initial and _final
'''
def homework2():
    result = {}
    # for each hour
    for hour in range(_initial,_final):
        # for each distribution
        data = []
        thresholds = calculateOMP(hour)
        
        # add optimistic and pesismitic values for this hour's package
        data.append(thresholds[0])
        data.append(thresholds[2])
        
        for _, dist in _distList:
            # adds media and varianza for each distribution 
            data.append(dist.media(thresholds[0],thresholds[2],thresholds[1]))
            data.append(dist.varianza(thresholds[0],thresholds[2],thresholds[1]))
            
        # add this hour data    
        result[hour] = data
    return result
    

''' 
    Calculate the optimistic, media and pessimistic value for a given hour
'''
def calculateOMP(hour):
    opt = hour * _lower_threshold_Boehm
    media = hour * _middle_threshold_Boehm
    pes = hour * _upper_threshold_Boehm
    
    return [opt, media, pes]


def asCSV(data, floatComma=True):
    dataAsCSV = ''
    separator = ';'
    newLine = '\n'
    # generate headers for the table
    headerDistributions = '' + separator +  ''      + separator +  ''       + separator
    headerTitles = 'Horas'   + separator +  'Opt'   + separator +  'Pes'    + separator
    for hour, _ in _distList:
        headerDistributions += hour + separator * 2
        headerTitles += 'Media' + separator + 'Varianza' + separator
    dataAsCSV += headerDistributions + newLine
    dataAsCSV += headerTitles + newLine
    
    # generate table data
    for hour in iter(data):
        distributions = data[hour]
        dataAsCSV += str(hour) 
        for hourData in distributions:
            dataAsCSV += separator + str(hourData) 
        dataAsCSV += newLine
    if floatComma:
        return dataAsCSV.replace('.',',')
    else:
        return dataAsCSV




''' ******************************************************************************
        Calcula los valores para las distribuciones configuradas y genera un
        archivo csv con los datos pronto para graficar
    ***************************************************************************'''
#if __name__ == '__main__':
def createFile(fileName=None, floatComma=True):
    _fileName = fileName
    if _fileName==None:
        today = datetime.now().strftime('%d-%m-%Y_%H-%M')
        _fileName = _filePath + 'practico2_IS3_' + today + '.csv'
    
    'get data as CSV '
    strData = generateData(floatComma)
    
    f = open(_fileName, 'w')
    f.write(strData)
    f.close()
    return _fileName
    
    
''' ******************************************************************************
        Calcula los valores para las distribuciones configuradas y retorna un 
        string en formato csv
    ***************************************************************************'''
def generateData(floatComma=True):
    'load distribution implementations'
    loadDistributions()
    
    'generate data'
    data = homework2()
    
    'return data as CSV '
    return asCSV(data, floatComma) 


